package com.example.myapplication;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * 系统控制服务
 * 提供屏幕控制、设备重启、APK安装等系统级功能
 */
public class SystemControlService {
    private static final String TAG = "SystemControlService";
    
    private final Context context;
    private final PowerManager powerManager;
    private final PackageManager packageManager;
    private final ActivityManager activityManager;

    public SystemControlService(Context context) {
        this.context = context;
        this.powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        this.packageManager = context.getPackageManager();
        this.activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    }

    /**
     * 检测设备是否具有root权限
     * @return 是否具有root权限
     */
    public boolean hasRootPermission() {
        try {
            // 方法1: 尝试执行简单的su命令
            Process process = Runtime.getRuntime().exec("su -c echo 'root_test'");
            process.waitFor();
            int exitValue = process.exitValue();
            Log.d(TAG, "Root权限检测 - 退出码: " + exitValue);
            if (exitValue == 0) {
                Log.d(TAG, "Root权限检测成功");
                return true;
            }
        } catch (Exception e) {
            Log.e(TAG, "Root权限检测异常: " + e.getMessage());
        }

        try {
            // 方法2: 检查su文件是否存在
            Process process = Runtime.getRuntime().exec("which su");
            process.waitFor();
            int exitValue = process.exitValue();
            Log.d(TAG, "su文件检测 - 退出码: " + exitValue);
            if (exitValue == 0) {
                Log.d(TAG, "su文件存在，可能有root权限");
                return true;
            }
        } catch (Exception e) {
            Log.e(TAG, "su文件检测异常: " + e.getMessage());
        }

        try {
            // 方法3: 检查/system/bin/su或/system/xbin/su
            java.io.File suFile1 = new java.io.File("/system/bin/su");
            java.io.File suFile2 = new java.io.File("/system/xbin/su");
            if (suFile1.exists() || suFile2.exists()) {
                Log.d(TAG, "su文件存在于系统目录");
                return true;
            }
        } catch (Exception e) {
            Log.e(TAG, "系统su文件检测异常: " + e.getMessage());
        }

        Log.d(TAG, "设备没有root权限");
        return false;
    }

    /**
     * 关闭屏幕
     * @return 操作结果
     */
    public SystemControlResult turnOffScreen() {
        try {
            // 使用新的ScreenControlService
            ScreenControlService screenControlService = new ScreenControlService(context);
            ScreenControlService.ScreenControlResult result = screenControlService.turnOffScreen();
            
            Log.d(TAG, "屏幕关闭结果: " + result.message);
            return new SystemControlResult(result.success, result.message, result.code);
            
        } catch (Exception e) {
            Log.e(TAG, "关闭屏幕失败", e);
            return new SystemControlResult(false, "关闭屏幕失败: " + e.getMessage(), "ERROR");
        }
    }

    /**
     * 开启屏幕
     * @return 操作结果
     */
    public SystemControlResult turnOnScreen() {
        try {
            // 使用新的ScreenControlService
            ScreenControlService screenControlService = new ScreenControlService(context);
            ScreenControlService.ScreenControlResult result = screenControlService.turnOnScreen();
            
            Log.d(TAG, "屏幕开启结果: " + result.message);
            return new SystemControlResult(result.success, result.message, result.code);
            
        } catch (Exception e) {
            Log.e(TAG, "开启屏幕失败", e);
            return new SystemControlResult(false, "开启屏幕失败: " + e.getMessage(), "ERROR");
        }
    }

    /**
     * 重启设备
     * @return 操作结果
     */
    public SystemControlResult rebootDevice() {
        try {
            // 先检测root权限
            if (!hasRootPermission()) {
                return new SystemControlResult(false, "重启设备失败: 设备没有root权限", "NO_ROOT");
            }

            // 使用Runtime执行重启命令
            Process process = Runtime.getRuntime().exec("su -c reboot");
            process.waitFor();
            int exitValue = process.exitValue();
            
            if (exitValue == 0) {
                Log.d(TAG, "设备重启命令已执行");
                return new SystemControlResult(true, "设备重启命令已执行", "REBOOT");
            } else {
                Log.e(TAG, "设备重启命令执行失败，退出码: " + exitValue);
                return new SystemControlResult(false, "设备重启命令执行失败", "COMMAND_FAILED");
            }
        } catch (Exception e) {
            Log.e(TAG, "重启设备失败", e);
            return new SystemControlResult(false, "重启设备失败: " + e.getMessage(), "ERROR");
        }
    }

    /**
     * 关机设备
     * @return 操作结果
     */
    public SystemControlResult shutdownDevice() {
        try {
            // 先检测root权限
            if (!hasRootPermission()) {
                return new SystemControlResult(false, "关机失败: 设备没有root权限", "NO_ROOT");
            }

            // 方法1: 使用shutdown命令
            try {
                Process process = Runtime.getRuntime().exec("su -c 'shutdown -h now'");
                process.waitFor();
                int exitValue = process.exitValue();
                Log.d(TAG, "shutdown命令执行 - 退出码: " + exitValue);
                
                if (exitValue == 0) {
                    Log.d(TAG, "shutdown命令已执行");
                    return new SystemControlResult(true, "shutdown命令已执行", "SHUTDOWN");
                }
            } catch (Exception e) {
                Log.e(TAG, "shutdown方法失败: " + e.getMessage());
            }

            // 方法2: 使用reboot -p命令（关机）
            try {
                Process process = Runtime.getRuntime().exec("su -c 'reboot -p'");
                process.waitFor();
                int exitValue = process.exitValue();
                Log.d(TAG, "reboot -p命令执行 - 退出码: " + exitValue);
                
                if (exitValue == 0) {
                    Log.d(TAG, "reboot -p命令已执行");
                    return new SystemControlResult(true, "reboot -p命令已执行", "SHUTDOWN");
                }
            } catch (Exception e) {
                Log.e(TAG, "reboot -p方法失败: " + e.getMessage());
            }

            // 方法3: 使用halt命令
            try {
                Process process = Runtime.getRuntime().exec("su -c 'halt'");
                process.waitFor();
                int exitValue = process.exitValue();
                Log.d(TAG, "halt命令执行 - 退出码: " + exitValue);
                
                if (exitValue == 0) {
                    Log.d(TAG, "halt命令已执行");
                    return new SystemControlResult(true, "halt命令已执行", "SHUTDOWN");
                }
            } catch (Exception e) {
                Log.e(TAG, "halt方法失败: " + e.getMessage());
            }

            // 方法4: 使用poweroff命令
            try {
                Process process = Runtime.getRuntime().exec("su -c 'poweroff'");
                process.waitFor();
                int exitValue = process.exitValue();
                Log.d(TAG, "poweroff命令执行 - 退出码: " + exitValue);
                
                if (exitValue == 0) {
                    Log.d(TAG, "poweroff命令已执行");
                    return new SystemControlResult(true, "poweroff命令已执行", "SHUTDOWN");
                }
            } catch (Exception e) {
                Log.e(TAG, "poweroff方法失败: " + e.getMessage());
            }

            return new SystemControlResult(false, "所有关机方法都失败了", "ALL_METHODS_FAILED");
            
        } catch (Exception e) {
            Log.e(TAG, "关机失败", e);
            return new SystemControlResult(false, "关机失败: " + e.getMessage(), "ERROR");
        }
    }

    /**
     * 安装APK文件
     * @param apkFilePath APK文件路径
     * @return 操作结果
     */
    public SystemControlResult installApk(String apkFilePath) {
        try {
            File apkFile = new File(apkFilePath);
            if (!apkFile.exists()) {
                return new SystemControlResult(false, "APK文件不存在: " + apkFilePath, "ERROR");
            }

            // 方法1: 使用PackageInstaller安装（推荐）
            if (installApkWithPackageInstaller(apkFile)) {
                return new SystemControlResult(true, "APK安装命令已执行", "APK_INSTALL");
            }

            // 方法2: 使用Intent安装（备用）
            if (installApkWithIntent(apkFile)) {
                return new SystemControlResult(true, "APK安装界面已打开", "APK_INSTALL");
            }

            return new SystemControlResult(false, "APK安装失败", "ERROR");

        } catch (Exception e) {
            Log.e(TAG, "安装APK失败", e);
            return new SystemControlResult(false, "安装APK失败: " + e.getMessage(), "ERROR");
        }
    }

    /**
     * 使用PackageInstaller安装APK
     * @param apkFile APK文件
     * @return 是否成功
     */
    private boolean installApkWithPackageInstaller(File apkFile) {
        try {
            PackageInstaller packageInstaller = packageManager.getPackageInstaller();
            PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                    PackageInstaller.SessionParams.MODE_FULL_INSTALL);
            params.setAppPackageName("com.example.installer"); // 临时包名
            
            int sessionId = packageInstaller.createSession(params);
            PackageInstaller.Session session = packageInstaller.openSession(sessionId);
            
            try (OutputStream out = session.openWrite("COSU", 0, -1);
                 FileInputStream in = new FileInputStream(apkFile)) {
                
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                session.fsync(out);
            }
            
            Intent intent = new Intent();
            android.app.PendingIntent pendingIntent = android.app.PendingIntent.getBroadcast(
                    context, 0, intent, android.app.PendingIntent.FLAG_UPDATE_CURRENT | android.app.PendingIntent.FLAG_IMMUTABLE);
            session.commit(pendingIntent.getIntentSender());
            session.close();
            return true;
            
        } catch (Exception e) {
            Log.e(TAG, "PackageInstaller安装失败", e);
            return false;
        }
    }

    /**
     * 使用Intent安装APK
     * @param apkFile APK文件
     * @return 是否成功
     */
    private boolean installApkWithIntent(File apkFile) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Intent安装失败", e);
            return false;
        }
    }

    /**
     * 获取系统信息
     * @return 系统信息
     */
    public SystemInfo getSystemInfo() {
        SystemInfo info = new SystemInfo();
        
        try {
            // 屏幕状态
            info.isScreenOn = powerManager != null && powerManager.isInteractive();
            
            // 内存信息
            ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
            activityManager.getMemoryInfo(memoryInfo);
            info.totalMemory = memoryInfo.totalMem;
            info.availableMemory = memoryInfo.availMem;
            info.memoryUsagePercent = (int) ((memoryInfo.totalMem - memoryInfo.availMem) * 100 / memoryInfo.totalMem);
            
            // 设备信息
            info.deviceModel = android.os.Build.MODEL;
            info.androidVersion = android.os.Build.VERSION.RELEASE;
            info.apiLevel = android.os.Build.VERSION.SDK_INT;
            
            // 系统运行时间
            info.systemUptime = android.os.SystemClock.elapsedRealtime();
            info.systemUptimeFormatted = formatUptime(info.systemUptime);
            
            // Root权限状态
            info.hasRootPermission = hasRootPermission();
            
        } catch (Exception e) {
            Log.e(TAG, "获取系统信息失败", e);
        }
        
        return info;
    }

    /**
     * 格式化开机时长
     * @param milliseconds 毫秒数
     * @return 格式化的时长字符串
     */
    public static String formatUptime(long milliseconds) {
        if (milliseconds < 0) {
            return "未知";
        }

        long seconds = milliseconds / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;

        if (days > 0) {
            return String.format("%d天%d小时%d分钟", days, hours % 24, minutes % 60);
        } else if (hours > 0) {
            return String.format("%d小时%d分钟", hours, minutes % 60);
        } else if (minutes > 0) {
            return String.format("%d分钟", minutes);
        } else {
            return String.format("%d秒", seconds);
        }
    }

    /**
     * 系统控制操作结果
     */
    public static class SystemControlResult {
        public boolean success;
        public String message;
        public String action;

        public SystemControlResult(boolean success, String message, String action) {
            this.success = success;
            this.message = message;
            this.action = action;
        }

        @Override
        public String toString() {
            return "SystemControlResult{" +
                    "success=" + success +
                    ", message='" + message + '\'' +
                    ", action='" + action + '\'' +
                    '}';
        }
    }

    /**
     * 系统信息数据类
     */
    public static class SystemInfo {
        // 屏幕状态
        public boolean isScreenOn;
        
        // 内存信息
        public long totalMemory;
        public long availableMemory;
        public int memoryUsagePercent;
        
        // 设备信息
        public String deviceModel;
        public String androidVersion;
        public int apiLevel;
        
        // 系统运行时间
        public long systemUptime;
        public String systemUptimeFormatted;
        
        // Root权限状态
        public boolean hasRootPermission;
        
        @Override
        public String toString() {
            return "SystemInfo{" +
                    "isScreenOn=" + isScreenOn +
                    ", memoryUsagePercent=" + memoryUsagePercent +
                    ", deviceModel='" + deviceModel + '\'' +
                    ", androidVersion='" + androidVersion + '\'' +
                    ", systemUptime=" + systemUptimeFormatted +
                    ", hasRootPermission=" + hasRootPermission +
                    '}';
        }
    }
}
